<?php
require_once 'include/inc.config.php';
require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/utils.php';
require_once APP_ROOT.'model/common/session.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/parameters.php';
require_once APP_ROOT.'model/common/site.php';



class Video {


    function insertVideo(&$data) {
    	$site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$data->set('enabled',1);

    	$tz =& new MyTimeZone();
        $data->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );

        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_video',
            array('site_id','category_id', 'category2_id', 'title', 'url', 'date_added', 'enabled','order_number'), 'video_id');
    }



    function &getRecord($id) {
        return DBC::FindRecord("SELECT V.*, C1.name as category1, C2.name as category2
        FROM sport_video V
        left outer join sport_categories C1 on V.category_id = C1.category_id
     	left outer join sport_categories C2 on V.category2_id = C2.category_id
        WHERE V.video_id = ". DBC::makeLiteral($id));
    }

    function updateVideo($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);

    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_video',
            array('site_id','category_id', 'category2_id', 'title', 'url', 'enabled','order_number'),
            "video_id=". DBC::makeLiteral($id));
    }




    function getVideoCount() {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
        $sql = "Select count(*) from sport_video where ".
        " (site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
    	return DBC::getOneValue($sql);
    }

    function getVideoMaxCustomOrder() {
        $site_id = Site::getSiteID();
    	return DBC::getOneValue("Select max(order_number) from sport_video where "." site_id = ".DBC::makeLiteral($site_id));
    }


    function denyVideo($video_id) {
        $data = new DataSpace();
        $data->set('enabled',0);

    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_video', array('enabled'),
            "video_id=". DBC::makeLiteral($video_id));
    }

    function publishVideo($video_id) {
        $data = new DataSpace();
        $data->set('enabled',1);

    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_video',
            array('enabled'), "video_id=". DBC::makeLiteral($video_id));
    }

    // get the next new video
    function &getNextNewVideo($current_video_id) {
        $site_id = Site::getSiteID();
        $sql = "select V.* from sport_video V, sport_video V2
        where V.video_id <> V2.video_id
        and V2.video_id = ".DBC::makeLiteral($current_article_id)."
        and V.date_added <= V2.date_added
        and (V.enabled = 0  or  V.enabled is null)
        and V.site_id = ".DBC::makeLiteral($site_id)."
        and V2.site_id = ".DBC::makeLiteral($site_id)."
        order by V.date_added desc limit 1";
        return DBC::FindRecord($sql);
    }


	function delete($id) {
        DBC::execute("DELETE FROM sport_video WHERE video_id=". DBC::makeLiteral($id));
    }

    function &getVideoList(&$Pager, &$request, &$responseModel,$options=null, $onlynew=false) {
        $site_id = Site::getSiteID();
     	//restore filter from session
     	Session::loadResponseModel($responseModel,'filter.video');
     	$sql = "select V.*, C1.name as category1, C2.name as category2
     		from sport_video V
     		left outer join sport_categories C1 on V.category_id = C1.category_id
     		left outer join sport_categories C2 on V.category2_id = C2.category_id";

     	if($options==null){
     		if ($onlynew) {
                $sql.=" where 1=1 and (V.enabled=0 or V.enabled is null)
                and V.site_id = ".DBC::makeLiteral($site_id)." ".Video::getVideoFilter($request, $responseModel)."
     		 	order by V.date_added desc ";
     		} else {
     			$sql.=" where 1=1
                and V.site_id = ".DBC::makeLiteral($site_id)." ".Video::getVideoFilter($request, $responseModel)."
     		 	order by ".Video::getVideoOrder($request, $responseModel);
     		}
            //print $sql;
        	return DBC::NewPagedRecordSet($sql, $Pager);
     	}else{
     		$sql.=" where 1=1
             and V.site_id = ".DBC::makeLiteral($site_id);
     		$sql.=" order by V.order_number, V.date_added desc, V.title ";
     		error_log("[SQL:]$sql");
     		//print $sql;
     		return DBC::NewPagedRecordSet($sql, $Pager);
     	}
     }

     function getVideoFilter(&$request,&$responseModel) {
      	$where = '';
      	$filter_video_id = $responseModel->get('filter_video_id');
        $video_id = $responseModel->get('video_id');
      	if ($filter_video_id)  $where .= ' and V.video_id = '.DBC::makeLiteral($video_id);

        $filter_title = $responseModel->get('filter_title');
        $title = $responseModel->get('title');
        if ($filter_title)  $where .= ' and V.title like '.DBC::makeLiteral('%'.$title.'%').'  ';

        $filter_category1 = $responseModel->get('filter_category1');
        $category1 = $responseModel->get('category1');
        if ($filter_category1)  $where .= ' and V.category_id = '.DBC::makeLiteral($category1);

        $filter_category2 = $responseModel->get('filter_category2');
        $category2 = $responseModel->get('category2');
        if ($filter_category2)  $where .= ' and V.category2_id = '.DBC::makeLiteral($category2);

        $filter_start_date = $responseModel->get('start_date_filter');
        $start_day = $responseModel->get('start_day');
        $start_month = $responseModel->get('start_month');
        $start_year = $responseModel->get('start_year');
        $start_date = gmmktime(0, 0, 0, $start_month, $start_day, $start_year);
        $tz =& new MyTimeZone();
        $start_date = $tz->timeLocal( $start_date );
        if ($filter_start_date) $where .= " and V.date_added>='".gmdate("Y.m.d",$start_date)."'";

        $filter_end_date = $responseModel->get('end_date_filter');
        $end_day = $responseModel->get('end_day');
        $end_month = $responseModel->get('end_month');
        $end_year = $responseModel->get('end_year');
        $end_date = gmmktime(0, 0, 0, $end_month, $end_day, $end_year);
        $end_date = $tz->timeLocal( $end_date );
        if ($filter_end_date) $where .= " and V.date_added<='".gmdate("Y.m.d",$end_date)."'";


        return $where;
      }

      function getVideoOrder(&$request,&$responseModel) {
      	$sortby = 'V.order_number desc, V.date_added desc';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return 'V.'.$sortby;
      	else return 'V.order_number desc, V.date_added desc';
      }


      function &getNewVideoList(&$Pager, &$request, &$responseModel) {
      	return Video::getVideoList($Pager, $request, $responseModel,null,true);
      }



     function &getPlaylistVideo($sport_id,$community_id) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();

     	$sql = "select V.* from sport_video V where V.enabled=1 ";
     	if($sport_id) $sql.=" and category_id=$sport_id";
     	if($community_id) $sql.=" and category2_id=$community_id ";
        $sql.=" and (V.site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
        $sql.=" order by V.order_number desc, V.date_added desc ";
     	//print  $sql;
        $rs =& DBC::NewRecordSet($sql);
        return $rs;

     }

     function &savePlaylistFile($sport_id,$community_id) {
        $filename =& Video::getPlaylistFilename($sport_id,$community_id);
        $content =& Video::getPlaylistFileContent($sport_id,$community_id);
        $fname = 'video/'.$filename;
        //print "Filename: ".$filename."<BR>\n".$content."<BR>\n";
   		if($ff = fopen($fname,'w'))    {
    		fwrite($ff,$content);
    		fclose($ff);

   		}
     }

     function &getPlaylistFilename($sport_id,$community_id) {

        $site_id = Site::getSiteID();
        $filename = 'playlist_'.$site_id.'_0_0_.xml';
     	if ($sport_id && $community_id) {
          $filename = 'playlist_'.$site_id.'_'.$sport_id.'_'.$community_id.'_.xml';
     	} else if ($sport_id) {
          $filename = 'playlist_'.$site_id.'_'.$sport_id.'_0'.'_.xml';
     	} else if ($community_id) {
          $filename = 'playlist_'.$site_id.'_'.'0_'.$community_id.'_.xml';
     	} else {
     	  $filename = 'playlist_'.$site_id.'_0_0_.xml';
     	}
     	return $filename;
     }

     function &getPlaylistFileContent($sport_id,$community_id) {

        // Start XML data string (playlist):
		$xml_data = '<?xml version="1.0" encoding="utf-8"?>'."\n";
		$xml_data .= '<playlist>'."\n";

		$cnt = 0;


		$list =& Video::getPlaylistVideo($sport_id,$community_id);

        $list->reset();
        // Build items into playlist
        while ($list->next()) {

        	$dataspace = $list->export();
        	$cnt++;

            $video_id = $list->get('video_id');
            $url = $list->get('url');
            $title = $list->get('title');

            // Open each item
			$xml_data .= '	<item>'."\n";

			// URL encode the string to avoid any issues with non-alpha-numeric characters
			$xml_data .= '		<filename>'.urlencode($url).'</filename>'."\n";

			// URL encode the string to avoid any issues with non-alpha-numeric characters
			$xml_data .= '		<title>'.urlencode($title).'</title>'."\n";

			// You can add more tags to the playlist, such as:
			// <comments></comments> // Used as the link on the graphic / ecommerce.
			// <artist></artist> // Used in the info display when a song is playing.
			// <visual></visual> // Used to populate the graphic / cover art.

			// Close each item:
			$xml_data .= '	</item>'."\n";

            //print_r($dataspace);

        }

		// Close XML data string (playlist):
		$xml_data .= '</playlist>'."\n";

		if ( ($sport_id || $community_id) && $cnt==0)  $xml_data =& Video::getPlaylistFileContent(0,0);
		return $xml_data;

     }


}

?>
